const Config = require('./Config.js');
const md5 = require('@/common/SDK/md5.min.js');
/* 弹窗封装 */
/* showToast */
function showToast(msg,callback,position='center',icon='none',){
	uni.showToast({
		icon:icon,
		title:msg,
		position:position,
		success:callback
	})
}
/* showModel */ 
function showModal(obj){
	uni.showModal({
		title: obj.title||"",
		content: obj.content||"",
		showCancel: obj.showCancel||false,
		cancelText: obj.cancelText||'取消',
		confirmText: obj.confirmText||'确定',
		success:obj.success,
		fail: obj.fail,
		complete: obj.complete,
		cancelColor:"#000000",
		confirmColor:"#FF7201"
	});
}


/********************************以下为签名信息********************************/
/**
 * 生成随机字符串
 */
const randomString = function (len) {
    len = len || 32;
    var $chars = 'ABC1DEFGH2IJK3LMNOQP4RSTU5VWXYZab6cdef8ghij7kmlnopq9rest0uvwxyz';
    var maxPos = $chars.length;
    var str = '';
    for (var i = 0; i < len; i++) {
        str += $chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return str;
}
/**
 * 生成时间戳
 */
const timestamp = function (systimeStr) {
    //兼容苹果手机
    systimeStr = systimeStr.replace(/-/g, '/');
    const systime = new Date(systimeStr);
    const total = (systime.getTime()) / 1000;
    return total;
}
/**
 * 按照键排序
 */
const KeySort = function (obj) {
    var newkey = Object.keys(obj).sort(function (x, y) {
        return x.toString().toLowerCase() > y.toString().toLowerCase() ? 1 : -1;
    });
    var newObj = {};
    for (var i = 0; i < newkey.length; i++) {
        newObj[newkey[i]] = obj[newkey[i]];
    }
    return newObj;
}
/**
 * 生成签名
 */
const signature = function (data, key) {
    //排序
    var obj = KeySort(data);
    //拼接待签名参数
    var signStr = [];

    for(var key in obj){
        if (key != "Signature" && obj[key] !== undefined) {
            if (obj[key] === null) { obj[key] = ''; }//处理null签名错误问题
            else if (typeof obj[key] == 'object') { obj[key] = JSON.stringify(obj[key]); }//处理对象类型签名错误问题
            else if (typeof obj[key] == 'boolean') { obj[key] = obj[key] ? 'True' : 'False'; }//处理接口bool类型首字母大写签名错误问题
            signStr.push(key + "=" + obj[key]);
        }
    };
    signStr = signStr.join('&');
    // return md5.md5(signStr);
		return signStr;
}

/**
 * 时效缓存对象
 */
const TimeStorage = {
    /**
     * 时效缓存key前缀
     */
    timekeyprefix: "TimeStorage_Expire_",
    /**
    * 获取缓存内容
    */
    Get: function (key, isRemove) {
        //1、获取时效
        var timestamp = uni.getStorageSync(TimeStorage.timekeyprefix + key);
        if (timestamp == "") {
            TimeStorage.Remove(key);
            return "";
        }
        //2、判断是否失效
        var timestamp_now = (new Date().getTime() / 1000);//获取当前时间
        if (timestamp_now > timestamp) {
            TimeStorage.Remove(key);
            return "";
        }
        var val = uni.getStorageSync(key);
        if (val == "") {
            TimeStorage.Remove(key);
            return "";
        }
        //获取的同时，移除当前缓存
        if (isRemove) {
            TimeStorage.Remove(key);
        }
        //3、返回缓存内容
        return val;
    },
	/* get */
	geted(key){
		let val = uni.getStorageSync(key);
		return val;
	},
    /**
     * 设置缓存内容
     */
    Set: function (key, data, seconds) {//缓存了数据，并且缓存了时间
        //1、缓存数据
        uni.setStorageSync(key, data);
        if (seconds != undefined && typeof (seconds) == "number") {
            //2、缓存有效时间戳
            var timestamp = (new Date().getTime() / 1000) + seconds;//设置有效时间
            uni.setStorageSync(TimeStorage.timekeyprefix + key, timestamp);
        }
    },
    /**
     * 移除缓存内容
     */
    Remove: function (key) {
        uni.removeStorageSync(key);
        uni.removeStorageSync(TimeStorage.timekeyprefix + key);
    }
}
 // 获取地理位置
 const getLocation=(that)=>{
	return new Promise(function(resolve,reject){
		uni.getLocation({
				type: 'wgs84',
				success: res=> {
					that.longitude=res.longitude;
					that.latitude=res.latitude;
					let pageroute=Pages(0).route;
					console.log(res)
					if(pageroute=="pages/tabBar/home/home"){
						that.$store.state.cityname="定位中"
					}
					uni.request({
							url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${res.latitude},${res.longitude}&key=${Config.mapKey}`,
							success: res => {
								that.city=res.data.result.ad_info.city;
								resolve(res)
							}
					})
				}
		});
	})
}
// 判断ios 与安卓
const isIOS=()=>{
	if(uni.getSystemInfoSync().platform === 'android'){
	    // console.log('运行Android上')
		return false
	}else{
	    // console.log('运行iOS上')
		return true
	}
}
//返回页面对象
const Pages=(i)=>{
	let index=i||1
	var pages = getCurrentPages();
	var page = pages[pages.length -index];
	return page;
	// #ifdef APP-PLUS
	var currentWebview = page.$getAppWebview();
	return currentWebview
	// #endif
}

// 手机验证
const isPoneAvailable=(str)=> {  
    var myreg=/^[1][3,4,5,6,7,8,9][0-9]{9}$/; 
	 let Str=trim(str,'g')
    if (!myreg.test(Str)) {  
        return false;  
    } else {  
        return true;  
    }  
} 

function trim(str, is_global) {
  var result;
  result = str.replace(/(^\s+)|(\s+$)/g, "");
  if (is_global && is_global.toLowerCase() == "g") {
    result = result.replace(/\s/g, "");
  }
  return result;
}
// 获取元素高度
// const getComputedHeight=(ele,_this)=>{
//   let query = uni.createSelectorQuery();
//   query.select('.'+ele).boundingClientRect(res => {
// 		
//   }).exec();
// }
/* 时间戳转日期格式  */
function add0(m){return m<10?'0'+m:m }
function formatDateTime(timestamp,hour=0){
	var time = new Date(timestamp);
	var y = time.getFullYear();
	var m = time.getMonth()+1;
	var d = time.getDate();
	var h = time.getHours();
	var mm = time.getMinutes();
	var s = time.getSeconds();
	if(hour==1){
		return y+'-'+add0(m)+'-'+add0(d)+' '+add0(h)+':'+add0(mm)+':'+add0(s);
	}
	if(hour==2){
		return y+'-'+add0(m)+'-'+add0(d)+' '+add0(h)+':'+add0(mm);
	}
	return y+'-'+add0(m)+'-'+add0(d);
}
/* 获取参数 a=1&b=2 */
function getQueryVariable(query,variable)
	{
	   var vars = query.split("&");
	   for (var i=0;i<vars.length;i++) {
			   var pair = vars[i].split("=");
			   if(pair[0] == variable){return pair[1];}
	   }
	   return(false);
	}
const showtip=(that,url)=>{
	if(!that.hasLogin){
		showToast("请先登录");
		setTimeout(()=>{
			let isFingerLogin = TimeStorage.geted('isFingerLogin')
			if(isFingerLogin){
				uni.navigateTo({
					url:"/pages/logins/login/fingerlogin"
				})
				return; 
			}
			uni.navigateTo({
				url:"/pages/login/login"
			})
		},800)
		return false;
	}
	uni.navigateTo({
		url:url
	})
}
/* 图片缓存 */
function lazyload(imgurl){
	return new Promise((resolve,rej)=>{
	var canUseImg="";
	// 1. 转换网络图片地址为本地缓存图片路径，判断该图片是否存在本地缓存  
	// http://...jpg -> md5  
	// 缓存目录 _downloads/image/(md5).jpg  
	// let image_url=Config.imgUrl+imgurl;//网络地址图片
	let image_url=imgurl;//网络地址图片
	let image_md5           = md5(image_url);  
	// var local_image_url     = '_doc/image/'+image_md5+'.png'; // 缓存本地图片url  
	var local_image_url     = '_doc/image/'+image_md5+'.png'; // 缓存本地图片url  
	// var absolute_image_path = plus.io.convertLocalFileSystemURL(local_image_url); // 平台绝对路径
	// 判断图片文件是否存在  
		plus.io.getImageInfo({
			src:local_image_url,
			success:(res)=>{
				if(res.width!=""){//存在图片
					// 1.1 存在，则直接拿取缓存图片  
					canUseImg=local_image_url;
					resolve(canUseImg)
				}else{
					//1.2不存在图片，请求图片，下载图片
					canUseImg=image_url;
					resolve(canUseImg)
					download_img(image_url,local_image_url);
				}
			},
			fail:(res)=>{
				//不存在图片
				canUseImg=image_url;
				download_img(image_url,local_image_url);
				resolve(canUseImg)
				rej(res)
			}
		});
	})
	// 1.2 下载图片缓存到本地  
	function download_img(image_url,local_image_url){  
		let download_task = plus.downloader.createDownload(image_url, {  
			filename: local_image_url // filename:下载任务在本地保存的文件路径  
		}, function(download, status) {  
			if(status != 200){  
				// 下载失败,删除本地临时文件  
				if(local_image_url != null){  
					plus.io.resolveLocalFileSystemURL(local_image_url, function(entry) {  
						entry.remove(function(entry) {  
							console.log("临时文件删除成功" + local_image_url);  
							// 重新下载图片  
							download_img(image_url,local_image_url);  
						}, function(e) {  
							console.log("临时文件删除失败" + local_image_url);  
						});  
					});  
				}  
			}else{  
				// 把下载成功的图片显示  
				console.log('下载成功')
			}  
		});  
		download_task.start();  
	}
}

module.exports = {
	showToast,
	showtip,
	showModal,
	TimeStorage:TimeStorage,
	/**
   * 随机字符串
   */
    RandomString: randomString,
    /**
     * 生成时间戳
     */
    Timestamp: timestamp,
    /**
     * 签名
     */
    Signature: signature,
	GetLocation:getLocation,
	isIOS:isIOS,
	trim:trim,
	Pages:Pages,
	isPoneAvailable,
	formatDateTime,
	getQueryVariable,
	lazyload
}
